<?php
namespace addons\vote\models;
use addons\member\models\Member;
use addons\vote\controllers\rank;
use system\Model;

class VoteLogModel extends Model {
	public $error = '';
	protected $auto = [
		['create_time' , 'time' , self::MODEL_INSERT , 'function']
	];
	public $maxTicket = 10;
	public $deparents = [
		1 => '财务部' ,
		2 => '测试中心',
		3 => '技术质量部' ,
		4 => '经济运行部' ,
		5 => '民品分厂' ,
		6 => '企业管理' ,
		7 => '人事部' ,
		8 => '特种品分厂' ,
		9 => '特种轴承事业部' ,
		10 => '轴承技术中心' ,
		11 => '装备配件分厂' ,
	];

	/**
	 * 获取用户的票数
	 * @param int $uid
	 * @return int|mixed
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午10:01
	 */
	public function getUserTicket($uid = 0){
		$model = new Member();
		$find = $model->where(['id' => $uid])->field('ticket,ticket_put')->find();
		if (!$find){
			return 0;
		}
		return $find;
	}

	/**
	 * 更新用户票数
	 * @param int $touid
	 * @param int $uid
	 * @param int $ticket
	 * @return bool|int
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午10:04
	 */
	public function updateUserTicket($touid = 0 , $uid = 0 , $ticket = 1){
		$model = new Member();
		$find = $model->where(['id' => $touid])->field('id')->find();
		if (!$find){
			return false;
		}
		if(!$model->where(['id' => $touid])->incField('ticket' , $ticket)){
			return false;
		}
		// 增加投票人已投票数
		if(!$model->where(['id' => $uid])->incField('ticket_put' , $ticket)){
			return false;
		}
		// 给被投票人增加票数
		rank::addScore($touid , 1);
		return true;
	}

	/**
	 * 校验数据
	 * @param $uid
	 * @param $touid
	 * @param string $maxTicketTips
	 * @param string $toUidTips
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-09 下午8:02
	 */
	public function ticketValid($uid , $touid , $maxTicketTips = '投票人剩余可用票数不足' , $toUidTips = '被投票人不是一个有效的用户'){
		if ($uid == $touid){
			$this->error = '被投票人不能是自己';
			return false;
		}
		$ticket = $this->getUserTicket($uid);
		if ($ticket['ticket_put'] >= $this->maxTicket){
			$this->error = $maxTicketTips;
			return false;
		}
		$toFind = $this->getUserTicket($touid);
		if (!$toFind){
			$this->error = $toUidTips;
			return false;
		}
		return true;
	}

	/**
	 * 是否可投票
	 * @param int $uid
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午8:23
	 */
	public function isVote($uid = 0){
		$ticket = $this->getUserTicket($uid);
		if ($ticket['ticket_put'] >= $this->maxTicket){
			return false;
		}
		return true;
	}

	/**
	 * 用户工号是否存在
	 * @param string $number
	 * @param int $uid
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:10
	 */
	public function userNumberExists($number = '' , $uid = 0){
		if ($number > 0){
			$model = new Member();
			$find = $model->where(['number' => $number])->field('id')->find();
			if ($find){
				if ($uid == $find['id']){
					return false; // 如果是同一个人，则可以保存成功
				}
				return true;
			}
			return false;
		}
		return true;
	}
}